package com.example.util;

import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.example.util.AsyncLoadImage.ImageCallback;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import ImageCache.ImageFileCache;
import ImageCache.ImageMemoryCache;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.widget.GridView;

/**
 * 线程池+缓存+Handler加载图片
 */
public class AsyncLoadImage {
	//缓存
	private Map<String,SoftReference<Drawable>> imageCache = new HashMap<String,SoftReference<Drawable>>();
	//线程池
	private ExecutorService executorService = Executors.newFixedThreadPool(20);//总共有10个线程循环使用
	//Hanlder
	//
	ImageMemoryCache memoryCache;
	//
	ImageFileCache fileCache;
	private Handler mHandler = new Handler();
	Bitmap result=null;
	public DisplayImageOptions options;
	public ImageLoader imageLoader;
	
	
	public interface ImageCallback {
		void imageLoad(Drawable image,String imageUrl);

		void imageLoad(Bitmap image, String imageUrl);
	}
	public AsyncLoadImage() {
		 imageLoader = ImageLoader.getInstance(); 
		 options = new DisplayImageOptions.Builder()
		 // .showStubImage(R.drawable.food)//设置图片在下载期间显示的图片
		// .showImageForEmptyUri(R.drawable.food)//设置图片Uri为空或是错误的时候显示的图片
		// .showImageOnFail(R.drawable.food)//设置图片加载/解码过程中错误时候显示的图片
		.cacheInMemory()//设置下载的图片是否缓存在内存中
		.cacheOnDisc()//设置图片缓存到本地缓存中
		.bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型
		.build(); 
	}
	
	/**
	 * 
	 * @param imageUrl 图片的地址
	 * @param imageCallback 回调接口
	 * @return 返回内存中缓存的图像 第一次返回null
	 */
	public Drawable loadDrawable(final String imageUrl,final ImageCallback imageCallback){
		
		//如果缓存中有则从缓存中取出来
		if(imageCache.containsKey(imageUrl)){
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			if(softReference.get()!=null){//判断是否有drawable
				return softReference.get(); //有则返回
			}
		}
		//使用线程池下载图片
		executorService.submit(new Runnable(){
			@Override
			public void run() {
				try {
//					final Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.jpg");
					final Drawable drawable = getDrawableFormUrl(imageUrl); //调用获取数据的方法
					imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));//将加载的图片放入到内存中
					mHandler.post(new Runnable(){
						@Override
						public void run() {
							imageCallback.imageLoad(drawable,imageUrl);//接口回调
							//imageCallback.imageLoad(result, imageUrl);
						}
					});
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
			
		});
		return null ;
	}
	/**
	 * 从网络上获取数据
	 */
	public Drawable getDrawableFormUrl(String imageUrl){
		
		
		Drawable drawable = null ;
		try {
			drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "iamgeSync");//image.jpg
		} catch (Exception e) {
			throw new RuntimeException();
		}
		return drawable ;
	}
	public Bitmap loadBitmap(final String imageUrl,final ImageCallback imageCallback) {
		result=memoryCache.getBitmapFromCache(imageUrl);
		if(result==null){
			//文件缓存中获取
			result=fileCache.getImage(imageUrl);
			if(result!=null){
				//添加到内存
				memoryCache.addBitmapToCache(imageUrl,result);
			}else{
				//使用线程池下载图片
				executorService.submit(new Runnable(){
					@Override
					public void run() {
						Drawable drawable= getDrawableFormUrl(imageUrl);
						//从网络获取
						//result=ImageGetFromHttp.downloadBitmap(imageUrl);
						result=setIcon(drawable);
							if(result!=null){
								fileCache.saveBitmap(result,imageUrl);
								memoryCache.addBitmapToCache(imageUrl,result);
							}
						mHandler.post(new Runnable(){
							@Override
							public void run() {
								imageCallback.imageLoad(result, imageUrl);
							}
						});
					}
				});
			}
		}
		return result;
	}
	 public Bitmap setIcon(Drawable drawable) {  
	    	Bitmap bitmap =Bitmap.createBitmap(drawable.getIntrinsicWidth(),
	                drawable.getIntrinsicHeight(), Config.RGB_565);
	        Canvas canvas = new Canvas(bitmap);
	        canvas.save();
	        canvas.rotate(360.0f, canvas.getWidth() / 2.0f, canvas.getHeight() / 2.0f);
	        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
	        drawable.draw(canvas);
	        canvas.restore();
	       return bitmap;  
	 }  

}
